package com.dunshan.dunshanmongodb.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoClientDbFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;


@Slf4j
@Component
@Aspect
public class MongoSwitchAop {


    @Autowired
    private MongoDbFactory mongoDbFactory;

    //获取配置文件的副本集连接
    @Value("${spring.data.mongodb.master}")
    private String masterUri;

    @Value("${spring.data.mongodb.slave}")
    private String slaveUri;

    @Pointcut("execution(* com.dunshan.dunshanmongodb.controller..*.*(..))")
    public void routeMongoDB() {

    }

    @Around("routeMongoDB()")
    public Object routeMongoDB(ProceedingJoinPoint joinPoint) {
        Object result = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //获取需要访问的项目数据库
        String header = request.getHeader("7d");
        String name = joinPoint.getSignature().getName();
        System.out.println("--方法名字-" + name);
        Object o = joinPoint.getTarget();

        Field[] fields = o.getClass().getDeclaredFields();

        for (Field field : fields) {
            System.out.println("--------->");
            System.out.println(field.getName());
        }
        MultiMongoTemplate mongoTemplate = null;
        SimpleMongoClientDbFactory simpleMongoClientDbFactory = null;
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                if (header != null && header.equals("7dgroup")) {
                    simpleMongoClientDbFactory = new SimpleMongoClientDbFactory(this.masterUri);
                    mongoTemplate = new MultiMongoTemplate( simpleMongoClientDbFactory);
                    //设置MongoFactory
                    mongoTemplate.setMongoDbFactory( simpleMongoClientDbFactory);
                    //重新赋值
                    field.set(o, mongoTemplate);
                } else {
                    simpleMongoClientDbFactory = new SimpleMongoClientDbFactory(this.slaveUri);
                    mongoTemplate = new MultiMongoTemplate( simpleMongoClientDbFactory);
                    //设置MongoFactory
                    mongoTemplate.setMongoDbFactory( simpleMongoClientDbFactory);
                    //重新赋值
                    field.set(o, mongoTemplate);
                }
                break;
            }
            try {
                result = joinPoint.proceed();
                //清理 TransmittableThreadLocal 的变量
                mongoTemplate.removeMongoDbFactory();
            } catch (Throwable t) {
                log.error("数据异常{}", t.getMessage());
            }
        } catch (Exception e) {
            log.error("数据异常！{}", e.getMessage());
        }
//
        return result;
    }

}
